﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace BaseSet.Entity.Common.Text
{
    /// <summary>
    /// 摘要算法 MD5
    /// </summary>
    public class MD5Def
    {
        /// <summary>
        /// 取字符串的MD5码 用指定的编码格式 如utf-8 得到如：46F2366A-B9D4-48C7-9E7B-00FB91F0E69A 的串
        /// ??? 可以使用格式化字符串
        /// </summary>
        /// <param name="s">待加密的字串</param>
        /// <param name="_input_charset">编码格式</param>
        public static string GetMD5(string s, string _input_charset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }

            string result = sb.ToString().ToUpper();
            result = result.Insert(8, "-");
            result = result.Insert(13, "-");
            result = result.Insert(18, "-");
            result = result.Insert(23, "-");

            return result;
        }

        /// <summary>
        /// utf-8编码取字符串的MD5码 用指定的编码格式 如utf-8 得到如：46F2366A-B9D4-48C7-9E7B-00FB91F0E69A 的串
        /// ??? 可以使用格式化字符串
        /// </summary>
        /// <param name="s">待加密的字串</param>
        /// <param name="_input_charset">编码格式</param>
        public static string GetMD5(string s)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(s));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }

            string result = sb.ToString().ToUpper();
            result = result.Insert(8, "-");
            result = result.Insert(13, "-");
            result = result.Insert(18, "-");
            result = result.Insert(23, "-");

            return result;
        }
    }
}
